package com.example.netcomponent.net.download;



import com.example.netcomponent.net.utils.LogUtils;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;

/**
 * Created by zengxianghui900 on 17/10/11.
 */

public class ProgressDownloadSubscriber<T> extends Subscriber<T> implements DownloadProgressListener {

    private HttpDownOnNextListener mListener;
    public ProgressDownloadSubscriber(HttpDownOnNextListener listener) {
        this.mListener = listener;
    }

    @Override
    public void onStart() {
        if (mListener != null){
            mListener.onStart();
        }
    }

    @Override
    public void onCompleted() {
        if (mListener != null){
            mListener.onComplete();
        }
    }

    @Override
    public void onError(Throwable e) {
        //存储一下下载文件错误
        LogUtils.saveLogToSD(LogUtils.ERROR_DOWNFILE,e.getMessage());
        if (mListener != null){
            mListener.onError(e);
        }
    }

    @Override
    public void onNext(T t) {
        if (mListener != null){
            mListener.onNext(t);
        }
    }

    //进度更新
    @Override
    public void update(long read, final long count, boolean done) {
        if (mListener != null) {
            /*接受进度消息，造成UI阻塞，如果不需要显示进度可去掉实现逻辑，减少压力*/
            rx.Observable.just(read).observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Action1<Long>() {
                        @Override
                        public void call(Long aLong) {
                            mListener.updateProgress(aLong,count);
//                            Log.e("zxh","aLong==" + aLong + ",count==" + count);
                        }
                    });
//            mListener.updateProgress(read,count);
        }
    }
}
